package com.nd.android.musicboxlibrary.ui.player;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.common.StarAppConfig;
import com.common.utils.StarAppUtils;
import com.google.gson.Gson;
import com.nd.android.musicboxlibrary.GlobalSetting;
import com.nd.android.musicboxlibrary.R;
import com.nd.android.musicboxlibrary.business.bean.FileInfo;
import com.nd.android.musicboxlibrary.business.bean.MusicInfo;
import com.nd.android.musicboxlibrary.business.comm.MagicNumber;
import com.nd.android.musicboxlibrary.business.comm.NdException;
import com.nd.android.musicboxlibrary.interf.IPlayerManager;
import com.nd.android.musicboxlibrary.interf.ManagerFactory;
import com.nd.android.musicboxlibrary.service.player.MusicService;
import com.nd.android.musicboxlibrary.ui.activity.MusicBox;
import com.nd.android.musicboxlibrary.ui.adapter.PlayerPagerAdapter;
import com.nd.android.musicboxlibrary.ui.common.BaseFragmentActivity;
import com.nd.android.musicboxlibrary.ui.common.DownloadSelectDialogUtil;
import com.nd.android.musicboxlibrary.ui.common.ImageLoaderUtil;
import com.nd.android.musicboxlibrary.ui.view.LyricView;
import com.nd.android.musicboxlibrary.ui.vip.VipIntroduceActivity;
import com.nd.android.musicboxlibrary.ui.vip.VipUtil;
import com.nd.android.musicboxlibrary.util.ConfigHelper;
import com.nd.android.musicboxlibrary.util.Log;
import com.nd.android.musicboxlibrary.util.MusicBoxUtils;
import com.nd.android.musicboxlibrary.util.NdThread;
import com.nd.android.musicboxlibrary.util.Network;
import com.nd.android.musicboxlibrary.util.ToastUtil;
import com.nd.rj.common.incrementalupdates.utils.LogUtil;
import com.ngds.library.downloadcenter.AppDownloadHelper;
import com.ngds.library.downloadcenter.AppDownloadHelperImpl;
import com.product.android.utils.LogUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 播放界面 Created 2014年9月11日 下午11:25:57
 *
 * @version
 * @author zxq
 * @see
 */
public class PlayerActivity extends BaseFragmentActivity implements MagicNumber {
	/**
	 *
	 * <br>Created 2014年11月28日 上午12:05:46
	 * @author       wat.ztag
	 */
	@Override
	public void initMagicNumber() {}
	private static List<Activity> subActivityList = null;
	private Context mContext;
	@SuppressLint("SimpleDateFormat")
	private SimpleDateFormat mSdf = new SimpleDateFormat("mm:ss");
	private int mMaxVolume;
	private SeekBar mSkbVolume;
	private SeekBar mSkbMusic;
	private TextView mTvPositon;
	private TextView mTvDuration;
	private TextView mTvSpecialName;
	private TextView mTvStarName;
	/** 普通用户下载普通音质，播放页面顶部，出现vip特权介绍提示 */
	private TextView mTvTopTipVip;
	private LinearLayout mLlVolume;
	private LinearLayout mLlDownload;
	private ImageView mIvMusicIcon;
	private ImageView mIvPlay;
	private ImageView mIvPause;
	private ImageView mIvLoopType;
	private ImageView mIvFav;
	private TextView mTvDownload;
	private TextView mTvHasMv;
	private TextView mTvIsHQ;
	private TextView mTvPlaymv;
	private int mCurrentVolume;
	private int mCurrentLoopType;
	// 循环类型图标
	private int[] mLoopTypeResource = { R.drawable.mbx_player_order_selector,
			R.drawable.mbx_player_looping_selector, R.drawable.mbx_player_random_selector};
	private BroadcastReceiver mReceiver = new MusicReceiver();
	private AudioManager mAudioManager;
	private ViewPager mVpPage;
	private PagerAdapter mAdapter;
	private LyricView mLyric;
	private MusicInfo mCurrentMusic;
	private int mBuffered = -1;


	/**
	 * 加入栈 Created 2014年9月16日 上午12:20:50
	 *
	 * @param activity
	 *            activity
	 * @author zxq
	 */
	public static void addSubActivity(Activity activity) {
		// 为空或者已经关闭了就不需要加入堆栈了吧  —— By HuangYK
		if (activity == null || activity.isFinishing()) {
			return;
		}
		//空保护
		if (subActivityList == null) {
			subActivityList = new ArrayList<Activity>();
		}
		subActivityList.add(activity);
	}

	/**
	 * 从栈中移除
	 * Created 2014年9月16日 上午12:20:53
	 * @author zxq
	 */
	public static void removeSubActivity() {
		// 空保护
		if (subActivityList == null || subActivityList.size() == 0) {
			return;
		}

		int size = subActivityList.size();
		Activity activity;
		for (int i = size - 1; i >= 0; i--) {
			//这里有可能为空，需要判断 —— By HuangYK
			activity = subActivityList.get(i);
			if (activity == null || activity.isFinishing()) {
				continue;
			}
			activity.finish();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.mbx_player_activity);
		mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
		subActivityList = new LinkedList<Activity>();
	}

	@Override
	public void onContentChanged() {
		super.onContentChanged();
		if (getIntent().hasExtra(MusicService.MUSIC_INFO)) {
			mCurrentMusic = (MusicInfo) getIntent().getSerializableExtra(MusicService.MUSIC_INFO);
		}
		// 返回按钮图标
		btnRight.setImageResource(R.drawable.mbx_top_more_selector);
		btnRight.setVisibility(View.VISIBLE);
		mIvLoopType = (ImageView) findViewById(R.id.iv_player_loop_type);
		mSkbVolume = (SeekBar) findViewById(R.id.skb_player_volume);
		mIvMusicIcon = (ImageView) findViewById(R.id.iv_player_music_icon);
		mLlVolume = (LinearLayout) findViewById(R.id.lay_player_volume);
		mLlDownload = (LinearLayout) findViewById(R.id.ll_player_download);
		mTvDownload = (TextView) findViewById(R.id.tv_player_download);
		mTvPlaymv = (TextView) findViewById(R.id.tv_player_playmv);
		//普通用户下载普通音质，播放页面顶部，出现vip特权介绍提示
		mTvTopTipVip = (TextView) findViewById(R.id.vp_top_tip_vip_tv);

		// 播放控制
		mIvPlay = (ImageView) findViewById(R.id.iv_player_play);
		mIvPause = (ImageView) findViewById(R.id.iv_player_pause);
		mTvPositon = (TextView) findViewById(R.id.tv_player_position);
		mSkbMusic = (SeekBar) findViewById(R.id.skb_player_music);
		mTvDuration = (TextView) findViewById(R.id.tv_player_duration);
		mTvDuration.setText(mSdf.format(0));
		mTvPositon.setText(mSdf.format(0));

		mVpPage = (ViewPager) findViewById(R.id.vp_player_page);
		View vMusicInfo = getLayoutInflater().inflate(R.layout.mbx_player_musicinfo, null);
		vMusicInfo.findViewById(R.id.rl_player_music_info).setOnClickListener(this);
		mTvSpecialName = (TextView) vMusicInfo.findViewById(R.id.tv_player_special_name);
		mTvStarName = (TextView) vMusicInfo.findViewById(R.id.tv_player_star_name);
		mTvHasMv = (TextView) vMusicInfo.findViewById(R.id.tv_player_has_mv);
		mTvIsHQ = (TextView) vMusicInfo.findViewById(R.id.tv_player_is_hq);
		mIvFav = (ImageView) vMusicInfo.findViewById(R.id.iv_player_fav);

		View vLyric = getLayoutInflater().inflate(R.layout.mbx_player_lyric, null);
		mLyric = (LyricView) vLyric.findViewById(R.id.lrcv_player_lyric);
		mLyric.setOnClickListener(this);
		List<View> lstViews = new ArrayList<View>();
		lstViews.add(vMusicInfo);
		lstViews.add(vLyric);
		mAdapter = new PlayerPagerAdapter(lstViews);
		mVpPage.setAdapter(mAdapter);

		initEvent();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MusicBoxUtils.getMusicServiceAction());
		filter.addAction(AppDownloadHelper.ACTION_DOWNLOAD_COMPLETE);
		filter.addAction(AppDownloadHelper.ACTION_DOWNLOAD_DELETE);
		registerReceiver(mReceiver, filter);

		txtTitle.setEllipsize(TruncateAt.END);
		txtTitle.setSingleLine(true);

		initTextView();//by jwb
		initTopTipVIPTV();//by jwb
	}

	@Override
	protected void onResume() {
		super.onResume();
		//by jiangwb
		//初始化，是否VIP，的标签,把函数体放在resume中，
		//是为了能够进入VIP结束页面，并完成充值之后，用户返回到这个页面会重新网络判断一次。
		VipUtil.initVipTag(this);

		// 获取系统最大音量
		mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		mSkbVolume.setMax(mMaxVolume);
		mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		mSkbVolume.setProgress(mCurrentVolume);
		// 循环类型
		mCurrentLoopType = ConfigHelper.getInstance(this).loadIntKey(MusicService.LOOP_TYPE, 0);
		mIvLoopType.setImageResource(mLoopTypeResource[mCurrentLoopType]);
		//if (mCurrentMusic == null) {
			mCurrentMusic = ManagerFactory.getPlayerInstance().getCurrentMusicInfo();			
//		}
		if (mCurrentMusic != null) {
			initMusicInfo(mCurrentMusic);
			int playerState = ManagerFactory.getPlayerInstance().getPlayerState();
			boolean isPlaying = (playerState == IPlayerManager.PLAYER_STATE_PLAYING
					|| playerState == IPlayerManager.PLAYER_STATE_PREPARING);
			mIvPause.setVisibility(isPlaying ? View.VISIBLE : View.GONE);
			mIvPlay.setVisibility(isPlaying ? View.GONE : View.VISIBLE);
			// 播放标记
			int seekTo = ConfigHelper.getInstance(PlayerActivity.this).loadIntKey(
					MusicService.MUSIC_SEEKTO, 0);
			Log.i("doSuccess() seekTo = " + seekTo);
			mTvPositon.setText(mSdf.format(seekTo));
			mSkbMusic.setProgress(seekTo);
		} else {
			mSkbMusic.setEnabled(false);
			mIvPause.setVisibility(View.GONE);
			mIvPlay.setVisibility(View.VISIBLE);
			txtTitle.setText(R.string.mbx_music_box);
		}
	}

	/**
	 * 初始化文本TextView
	 */
	private void initTextView(){
		StarAppUtils.setViewTypeFace(mTvPositon, false);//设置字体类型
		StarAppUtils.setViewTypeFace(mTvDuration, false);//设置字体类型
		StarAppUtils.setViewTypeFace(mTvSpecialName, false);//设置字体类型
		StarAppUtils.setViewTypeFace(mTvStarName, false);//设置字体类型
		StarAppUtils.setViewTypeFace(mTvTopTipVip, false);//设置字体类型
		StarAppUtils.setViewTypeFace(mTvDownload, false);//设置字体类型
		StarAppUtils.setViewTypeFace(mTvHasMv, false);//设置字体类型
		StarAppUtils.setViewTypeFace(mTvIsHQ, false);//设置字体类型
		StarAppUtils.setViewTypeFace(mTvPlaymv, false);//设置字体类型
	}

	/** 初始化vip提示文本
	 *   普通用户下载普通音质，播放页面顶部，出现vip特权介绍提示
	 *    Created 2014-11-13 下午16：32：:21
	 *    @author jwb
	 *  */
	private void initTopTipVIPTV(){
		if(mTvTopTipVip == null){
			LogUtils.e("PlayerActivity.java", "initTopTipVIPTV() - mTvTopTipVip为null");
			return;
		}
		mTvTopTipVip.setOnClickListener(PlayerActivity.this);
		mTvTopTipVip.setText(Html.fromHtml("正在下载普通音质，点击查看<font color='#d93572'>VIP特权</font>" + ">>") );
		//mTvTopTipVip.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
		mTvTopTipVip.setMinHeight(100);
	}

	/**
	 *    显示“vip特权介绍提示 ”
	 *    普通用户下载普通音质，播放页面顶部，出现vip特权介绍提示
	 *    Created 2014-11-13 下午16：33：:21
	 *    @author jwb
	 */
	private void showTopTipVIPTV(final boolean isDownloadHQ){
		if(! StarAppConfig.getBooleanConfig(StarAppConfig.CONFIG_VERSION1_8)){
			return ;
		}
		if(mTvTopTipVip == null){
			LogUtils.e("PlayerActivity.java -- jiangwb", "showTopTipVIPTV() - mTvTopTipVip为null");
			return;
		}
		//vip用户也能显示
		//		if(VipUtil.isVip()){//判断是否是VIP会员，如果不是，就显示，如果是，就不显示
		//			return;
		//		}

		runOnUiThread( new Runnable() {
			@Override
			public void run() {
				if(isDownloadHQ){
					mTvTopTipVip.setText(Html.fromHtml("正在下载HQ音质，点击查看<font color='#d93572'>VIP特权</font>" + ">>") );
				}else{
					mTvTopTipVip.setText(Html.fromHtml("正在下载普通音质，点击查看<font color='#d93572'>VIP特权</font>" + ">>") );
				}
				mTvTopTipVip.setVisibility(View.VISIBLE);
			}
		});

	}

	/**
	 *    隐藏“vip特权介绍提示 ”
	 *    普通用户下载普通音质，播放页面顶部，出现vip特权介绍提示
	 *    Created 2014-11-13 下午16：34：:21
	 *    @author jwb
	 */
	private void hideTopTipVIPTV(){
		LogUtils.d("PlayerActivity.java -- jiangwb",  "hideTopTipVIPTV() - start");
		if(! StarAppConfig.getBooleanConfig(StarAppConfig.CONFIG_VERSION1_8)){
			return ;
		}
		if(mTvTopTipVip == null){
			LogUtils.e("PlayerActivity.java", "hideTopTipVIPTV() -mTvTopTipVip为null");
			return;
		}

		runOnUiThread( new Runnable() {
			@Override
			public void run() {
				mTvTopTipVip.setVisibility(View.GONE);
				LogUtils.d("PlayerActivity.java -- jiangwb",  "hideTopTipVIPTV() - end");
			}
		} );
	}


	/**
	 * 初始化事件
	 * Created 2014-7-6 上午11:03:21
	 * @author zxq
	 */
	private void initEvent() {
		OnSeekBarChangeListener listener = new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// 结束拖动
				if (seekBar.getId() == R.id.skb_player_music) {
					int progress = seekBar.getProgress();
					if (progress > mBuffered && mBuffered != -1) {
						return;
					}
					ManagerFactory.getPlayerInstance().seekTo(PlayerActivity.this, progress);
					mLyric.setScrolled(false);
				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				if (fromUser) {
					int id = seekBar.getId();

					if (id == R.id.skb_player_music) {
						mTvPositon.setText(mSdf.format(progress));
						if (progress >= mBuffered && mBuffered != -1) {
							return;
						}
						mLyric.setScrolled(true);
						mLyric.update(progress);

						// 音量调节
					} else if (id == R.id.skb_player_volume) {
						mCurrentVolume = progress;
						changeVolume(mCurrentVolume);

					}
				}
			}
		};
		mSkbVolume.setOnSeekBarChangeListener(listener);
		mSkbMusic.setOnSeekBarChangeListener(listener);

		mVpPage.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				mLyric.setScrolled(false);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (mCurrentMusic == null && id != R.id.btnRight && id != R.id.btnLeft) {
			return;
		}

		if (id == R.id.btnRight) {
			startActivity(new Intent(this, MusicBox.class));

			// 分享，预留，暂无此功能
		} else if (id == R.id.iv_player_share) {
			ToastUtil.showShort(PlayerActivity.this, R.string.mbx_common_unrealize);

			// 喜欢按钮
		} else if (id == R.id.iv_player_fav) {
			likeMusic();

			// 点击显示菜单面板
		} else if (id == R.id.lrcv_player_lyric || id == R.id.rl_player_music_info
				|| id == R.id.vp_player_page) {
			showMenuView();

			// 加入下载列表
		} else if (id == R.id.tv_player_download) {
			//			add2DownLoadList(); // by jiangwb ,点击弹出音质选项
			if(StarAppConfig.getBooleanConfig(StarAppConfig.CONFIG_VERSION1_8)){
				//showDownloadDlg(mCurrentMusic.getSize() , mCurrentMusic.getHQSize());// by jiangwb ,点击弹出音质选项
				DownloadSelectDialogUtil.showDownloadDlg(mContext, VipUtil.isVip(),
						mCurrentMusic,
						new DownloadSelectDialogUtil.OnClickListener() {
					@Override
					public void onRightBtnClicked(boolean isHQ) {
						//确认下载，加入到下载列表中
						add2DownLoadListFor1_8(mCurrentMusic , isHQ);
					}
				});
			}else{
				//确认下载，加入到下载列表中,by jiangwb
				add2DownLoadList();
			}
			// 播放MV
		} else if (id == R.id.tv_player_playmv) {
			ToastUtil.showShort(PlayerActivity.this, R.string.mbx_common_unrealize);

			// 播放顺序
		} else if (id == R.id.iv_player_loop_type) {
			changeLoopType();

			// 播放
		} else if (id == R.id.iv_player_play && mCurrentMusic != null) {
			ManagerFactory.getPlayerInstance().play(PlayerActivity.this);
			mIvPlay.setVisibility(View.GONE);
			mIvPause.setVisibility(View.VISIBLE);

			// 暂停
		} else if (id == R.id.iv_player_pause && mCurrentMusic != null) {
			ManagerFactory.getPlayerInstance().pause(PlayerActivity.this);
			mIvPause.setVisibility(View.GONE);
			mIvPlay.setVisibility(View.VISIBLE);

			// 上一首
		} else if (id == R.id.iv_player_prev && mCurrentMusic != null) {
			ManagerFactory.getPlayerInstance().prev(PlayerActivity.this);
			mSkbMusic.setProgress(0);
			mSkbMusic.setSecondaryProgress(0);
			mTvPositon.setText(mSdf.format(0));
			hideTopTipVIPTV();
			// 下一首
		} else if (id == R.id.iv_player_next && mCurrentMusic != null) {
			ManagerFactory.getPlayerInstance().next(PlayerActivity.this);
			mSkbMusic.setProgress(0);
			mSkbMusic.setSecondaryProgress(0);
			mTvPositon.setText(mSdf.format(0));
			hideTopTipVIPTV();
			//vip特权介绍
		} else if(id == R.id.vp_top_tip_vip_tv ){
			if( StarAppConfig.getBooleanConfig(StarAppConfig.CONFIG_VERSION1_8)){
				//进入到VIP介绍界面，by jwb
				startActivity(new Intent(mContext, VipIntroduceActivity.class));
			}
		}  else {
			super.onClick(v);
			return;
		}
	}

	/**
	 * 喜欢歌曲
	 * Created 2014-7-15 下午10:03:23
	 * @author zxq
	 */
	private void likeMusic() {
		// 已经是喜欢的歌曲，现在要取消喜欢
		if (mIvFav.isSelected()) {
			new AlertDialog.Builder(PlayerActivity.this).setTitle(R.string.mbx_hint)
			.setMessage(R.string.mbx_confirm_unlike_music)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setPositiveButton(R.string.mbx_confirm, new OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					startLikeMusicTask(false);
					mIvFav.setSelected(false);
				}
			}).setNegativeButton(R.string.mbx_cancel, null).show();
		} else {
			// 加入喜欢歌曲列表
			startLikeMusicTask(true);
			mIvFav.setSelected(true);
		}
	}

	/**
	 * 启动喜欢歌曲线程
	 * Created 2014-7-21 下午11:43:02
	 * @author zxq
	 */
	private void startLikeMusicTask(final boolean isLikeAction) {
		new Thread() {
			@Override
			public void run() {
				if (isLikeAction) {
					ManagerFactory.getPlaylistInstance(getApplicationContext()).likeMusic(
							mCurrentMusic);
				} else {
					ManagerFactory.getPlaylistInstance(getApplicationContext()).unLikeMusic(
							mCurrentMusic);
				}
			}
		}.start();
	}

	/**
	 * 加入下载列表
	 * Created 2014-7-15 下午10:03:01
	 * @author zxq
	 */
	private void add2DownLoadList() {
		// 还未加入下载列表
		if (!mTvDownload.isSelected()) {

			if (mCurrentMusic.isDownLoaded() || mCurrentMusic.isDownLoading()) {
				// 正在下载，或者已下载成功的，跳过；
				ToastUtil.showShort(PlayerActivity.this, R.string.mbx_music_downloading);
				return;
			} else {
				LogUtils.d("PlayerActivity.java -- jiangwb", ">>> add2DownLoadList() 加入到下载列表 <<<");
				ManagerFactory.getDownloadInstance(getApplicationContext())
				.addMusic2DownloadList(mCurrentMusic, false);
				ManagerFactory.getPlayerInstance().initMusicList(PlayerActivity.this);
				if (Network.isNetworkAvaliable(PlayerActivity.this)) {
					ToastUtil.showShort(PlayerActivity.this, R.string.mbx_added_to_download_list);
				} else {
					ToastUtil.showShort(PlayerActivity.this, R.string.mbx_no_net_for_download);
				}
			}
			//mTvDownload.setSelected(true);
		} else {
			if (mCurrentMusic.isDownLoaded()) {
				ToastUtil.showShort(PlayerActivity.this, R.string.mbx_music_is_downloaded);
			} else {
				ToastUtil.showShort(PlayerActivity.this, R.string.mbx_music_downloading);
			}
		}
	}

	/**
	 * 加入下载列表
	 * Created 2014-11-26 下午20:03:01
	 * @author jiangwb
	 */
	private void add2DownLoadListFor1_8(final MusicInfo musicInfo , final boolean isDownloadHQ) {
		if(musicInfo ==  null){
			return ;
		}
		boolean isSDExitHQ = false; //sd卡是否保存当前歌曲对应的HQ音质的文件
		boolean isSDExitNo = false;//sd卡是否保存当前歌曲对应的普通音质的文件
		if(!TextUtils.isEmpty(musicInfo.getHQMusicPath())){
			isSDExitHQ = new File(musicInfo.getHQMusicPath()).exists();
		}
		if(!TextUtils.isEmpty(musicInfo.getMusicPath())){
			isSDExitNo = new File(musicInfo.getMusicPath()).exists();
		}
		// 还未加入下载列表
		if(musicInfo.isDownLoading()){//歌曲正在下载中。。。
			ToastUtil.showShort(PlayerActivity.this, R.string.mbx_music_downloading);
		}else{
			if(isDownloadHQ == false && musicInfo.isDownLoaded() &&   isSDExitNo){
				//普通歌曲已经下载,用户不需要在下载普通歌曲了
				ToastUtil.showShort(PlayerActivity.this, R.string.mbx_music_is_downloaded);
			}else if( isSDExitHQ && musicInfo.isDownLoaded()){
				//HQ歌曲已经下载,用户不需要在下载HQ歌曲了,因为有HQ文件了，所以，也不能下载普通的了
				ToastUtil.showShort(PlayerActivity.this, R.string.mbx_music_is_downloaded);
			}else{
				//如果已经下载了普通音质，则VIP用户可以继续再下载HQ文件，下载成功后，覆盖普通音质文件
				new NdThread() {
					@Override
					protected Object doInBackground() {
						//						musicInfo.setDownLoaded(false);
						//						musicInfo.setDownLoading(false);
						ManagerFactory.getDownloadInstance(getApplicationContext()).addMusic2DownloadList(musicInfo , isDownloadHQ);
						showTopTipVIPTV(isDownloadHQ);//显示“vip特权介绍提示 ”
						return null;
					}

					@Override
					protected void doSuccess(Object result) {
						ManagerFactory.getPlayerInstance().initMusicList(PlayerActivity.this);
					}

					@Override
					protected void doFail(NdException e) {}
				}.execute();
				//mTvDownload.setSelected(true);
				if (Network.isNetworkAvaliable(PlayerActivity.this)) {
					ToastUtil.showShort(PlayerActivity.this, R.string.mbx_added_to_download_list);
				} else {
					ToastUtil.showShort(PlayerActivity.this, R.string.mbx_no_net_for_download);
				}
			}
		}
	}

	/**
	 * 更改循环类型
	 * Created 2014-7-15 下午10:01:19
	 * @author zxq
	 */
	private void changeLoopType() {
		mCurrentLoopType++;
		mCurrentLoopType %= mLoopTypeResource.length;
		Log.i("zxq", "mCurrentLoopType = " + mCurrentLoopType);
		mIvLoopType.setImageResource(mLoopTypeResource[mCurrentLoopType]);
		ManagerFactory.getPlayerInstance().updateLoopType(PlayerActivity.this, mCurrentLoopType);
	}

	/**
	 * 显示菜单面板
	 * Created 2014-7-14 上午12:47:33
	 * @author zxq
	 */
	private void showMenuView() {
		if (View.GONE == mLlVolume.getVisibility()) {
			mLlVolume.setVisibility(View.VISIBLE);
			mLlDownload.setVisibility(View.VISIBLE);
			mSkbVolume.setProgress(mCurrentVolume);
		} else {
			mLlVolume.setVisibility(View.GONE);
			mLlDownload.setVisibility(View.GONE);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		// 减小音量
		case KeyEvent.KEYCODE_VOLUME_DOWN:
			if (mCurrentVolume > 0) {
				mCurrentVolume--;
				changeVolume(mCurrentVolume);
			}
			// return View.VISIBLE == mLlVolume.getVisibility();
			return true;

			// 增大音量
		case KeyEvent.KEYCODE_VOLUME_UP:
			if (mCurrentVolume < mMaxVolume) {
				mCurrentVolume++;
				changeVolume(mCurrentVolume);
			}
			// return View.VISIBLE == mLlVolume.getVisibility();
			return true;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 改变音量
	 * Created 2014-7-12 上午12:41:38
	 * @author zxq
	 */
	private void changeVolume(int volume) {
		mSkbVolume.setProgress(volume);
		int flag = View.VISIBLE == mLlVolume.getVisibility() ? 0 : AudioManager.FLAG_SHOW_UI;
		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, flag);
	}

	/**
	 * 销毁
	 * Created 2014-7-6 下午2:21:07
	 * @author zxq
	 */
	@Override
	protected void onDestroy() {
		if (mReceiver != null) {
			unregisterReceiver(mReceiver);
		}
		ConfigHelper.getInstance(this).removeKey(ConfigHelper.CONFIG_KEY_TAB_INDEX);

		super.onDestroy();
	}

	/**
	 * 音乐播放广播接收器
	 * Created 2014-7-10 下午10:51:32
	 * @version PlayerActivity
	 * @author zxq
	 * @see
	 */
	private class MusicReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// 播放相关广播
			if (action.equals(MusicBoxUtils.getMusicServiceAction())) {
				// 当前播放歌曲信息
				if (intent.hasExtra(MusicService.MUSIC_INFO)) {
					MusicInfo musicInfo = (MusicInfo) intent
							.getSerializableExtra(MusicService.MUSIC_INFO);
					if (!musicInfo.equals(mCurrentMusic)) {
						initMusicInfo(musicInfo);
					}
				}
				// 当前播放进度
				if (intent.hasExtra(MusicService.MUSIC_POSITION)) {
					int positon = intent.getIntExtra(MusicService.MUSIC_POSITION, 0);
					mSkbMusic.setProgress(positon);
					mTvPositon.setText(mSdf.format(positon));
					mIvPlay.setVisibility(View.GONE);
					mIvPause.setVisibility(View.VISIBLE);
					mLyric.update(positon);
				}
				// 播放总时长
				if (intent.hasExtra(MusicService.MUSIC_DURATION)) {
					int duration = intent.getIntExtra(MusicService.MUSIC_DURATION, 0);
					mSkbMusic.setMax(duration);
					mTvDuration.setText(mSdf.format(duration));
				}
				// 缓冲进度
				if (intent.hasExtra(MusicService.MUSIC_BUFFERED)) {
					mBuffered = intent.getIntExtra(MusicService.MUSIC_BUFFERED, 0);
					mSkbMusic.setSecondaryProgress(mBuffered);
				}
				// 播放状态改变
				if (intent.hasExtra(MusicService.PLAYER_ACTION)) {
					int playAction = intent.getIntExtra(MusicService.PLAYER_ACTION,
							MusicService.ACTION_PLAY);
					switch (playAction) {
					case MusicService.ACTION_STOP:
						mSkbMusic.setProgress(0);
						mIvPlay.setVisibility(View.VISIBLE);
						mIvPause.setVisibility(View.GONE);
						mSkbMusic.setSecondaryProgress(0);
						mTvPositon.setText(mSdf.format(0));
						mLyric.setPaused(true);
						break;

					case MusicService.ACTION_PAUSE:
						mIvPlay.setVisibility(View.VISIBLE);
						mIvPause.setVisibility(View.GONE);
						mLyric.setPaused(true);
						break;

					default:
						mLyric.setPaused(false);
						mIvPlay.setVisibility(View.GONE);
						mIvPause.setVisibility(View.VISIBLE);
						break;
					}
				}
			} else if (AppDownloadHelper.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
				try {
					LogUtils.d("PlayerActivity.java -- jiangwb", "接收到下载歌曲完成命令 -- start");
					long downloadId = intent.getLongExtra(AppDownloadHelper.EXTRA_DOWNLOAD_ID, 0);
					String url = intent.getStringExtra(AppDownloadHelper.EXTRA_DOWNLOAD_URI);
					AppDownloadHelper appDownloadHelperImpl = AppDownloadHelperImpl.getInstance(
							getApplicationContext());
					if (!TextUtils.isEmpty(appDownloadHelperImpl.getFileName(downloadId))) {
						String description = appDownloadHelperImpl.getDescription(context, url);
						FileInfo fileInfo = new Gson().fromJson(description, FileInfo.class);
						if (fileInfo != null &&(fileInfo.getType() == FileInfo.TYPE_MUSIC
								|| fileInfo.getType() == FileInfo.TYPE_HQ_MUSIC)) {
							if (mCurrentMusic != null &&
									((mCurrentMusic.getId() != 0 && mCurrentMusic.getId() == fileInfo.getId())
											|| (mCurrentMusic.getHQId() != 0 && mCurrentMusic.getHQId() == fileInfo.getHQId()))) {
								// 下载完成
								if(mCurrentMusic.getHQId() == fileInfo.getHQId()){//HQ音质下载完成，覆盖普通音质
									//////
									mCurrentMusic.setHQ(true);
								}
								mCurrentMusic.setDownLoading(false);
								mCurrentMusic.setDownLoaded(true);
								mTvDownload.setSelected(true);
								ManagerFactory.getPlayerInstance().initMusicList(getApplicationContext());
								hideTopTipVIPTV();//下载成功后，隐藏“vip特权介绍提示 ”by jwb
								LogUtils.d("PlayerActivity.java -- jiangwb", "接收到下载歌曲完成命令 -- end");
							}
						}
					}
				} catch (Exception e) {
					Log.e("PlayerActivity.java -- jiangwb","ACTION_DOWNLOAD_COMPLETE Player",e);
				}
			}else if( AppDownloadHelper.ACTION_DOWNLOAD_DELETE.equals(action)){
				LogUtils.d("PlayerActivity.java -- jiangwb", "接收到删除歌曲完成命令 -- start");
				try {
					long fileID = intent.getLongExtra(AppDownloadHelper.EXTRA_FILE_ID, 0);
					int type = intent.getIntExtra(AppDownloadHelper.EXTRA_FILE_TYPE , 0 );
					if (type == FileInfo.TYPE_MUSIC || type == FileInfo.TYPE_HQ_MUSIC) {
						if (mCurrentMusic != null &&
								((mCurrentMusic.getId() != 0 && mCurrentMusic.getId() == fileID)
										|| (mCurrentMusic.getHQId() != 0 && mCurrentMusic.getHQId() == fileID))) {
							//删除下载列表的歌曲的通知
							hideTopTipVIPTV();//下载被删除后，同样隐藏“vip特权介绍提示 ”by jwb
							mCurrentMusic.setDownLoading(false);
							mCurrentMusic.setDownLoaded(false);
							mTvDownload.setSelected(false);
							ManagerFactory.getPlayerInstance().initMusicList(getApplicationContext());
							LogUtils.d("PlayerActivity.java -- jiangwb", "接收到删除歌曲命令 -- end");
						}
					}
				}catch (Exception e) {
					Log.e("PlayerActivity.java -- jiangwb","ACTION_DOWNLOAD_DELETE Player",e);
				}
			}
		}
	};

	/**
	 * 初始化歌曲信息
	 * Created 2014年9月11日 下午11:26:54
	 * @param musicInfo 歌曲
	 * @author zxq
	 */
	private void initMusicInfo(final MusicInfo musicInfo) {
		if (musicInfo == null) {
			return;
		}
		mSkbMusic.setEnabled(true);
		mSkbMusic.setProgress(0);
		mSkbMusic.setSecondaryProgress(0);
		mTvPositon.setText(mSdf.format(0));
		new Thread() {
			@Override
			public void run() {
				mLyric.read(musicInfo.getLrcPath());
				mLyric.update(0);
			};
		}.start();
		// 当前播放歌曲
		txtTitle.setText(musicInfo.getMusicName());
		mTvSpecialName.setText(musicInfo.getSpecialName());
		mTvDownload.setSelected(musicInfo.isDownLoaded());
		LogUtils.d("PlayerActivity.java -- jiangwb", "刷新mTvDownload的状态" + mTvDownload.isSelected() 
				+ " isDownloading:" + musicInfo.isDownLoading());
		// mTvDownload.setText(musicInfo.isDownLoaded() ? R.string.downloaded : R.string.download);
		mTvPlaymv.setVisibility(musicInfo.isHasMv() ? View.VISIBLE : View.GONE);
		mTvStarName.setText(musicInfo.getSingerName());
		mTvHasMv.setVisibility(musicInfo.isHasMv() ? View.VISIBLE : View.GONE);
		if(StarAppConfig.getBooleanConfig(StarAppConfig.CONFIG_VERSION1_8)){
			mTvIsHQ.setVisibility(View.VISIBLE);
			mTvIsHQ.setBackgroundColor(getResources().getColor(R.color.mbx_font_lyric_gray));
			//有HQid ,hq文件以及下载完了，再显示HQ标志 by jiangwb
			if(musicInfo.getHQId() > 0 && VipUtil.fileExist(musicInfo.getHQMusicPath())){
				mTvIsHQ.setBackgroundColor(getResources().getColor(R.color.mbx_font_lyric_pink));
			}else{
				mTvIsHQ.setBackgroundColor(getResources().getColor(R.color.mbx_font_lyric_gray));
			}
			//			mTvIsHQ.setBackgroundColor(musicInfo.isHQ() ?  getResources().getColor(R.color.mbx_font_lyric_pink): getResources().getColor(R.color.mbx_font_lyric_gray));
		}else{
			if(musicInfo.isHQ()){
				mTvIsHQ.setBackgroundColor(getResources().getColor(R.color.mbx_font_lyric_pink));			
				mTvIsHQ.setVisibility(View.VISIBLE);
			}else{
				mTvIsHQ.setBackgroundColor(getResources().getColor(R.color.mbx_font_lyric_gray));			
				mTvIsHQ.setVisibility(View.GONE);
			}
		}
		mIvFav.setSelected(musicInfo.isFaved());
		mIvMusicIcon.setImageResource(R.color.mbx_transparent);
		ImageLoaderUtil.displayPic(musicInfo.getImgUrl(GlobalSetting.MUSIC_IMAGE_SIZE),
				mIvMusicIcon);

		// 播放时长
		int duration = ConfigHelper.getInstance(PlayerActivity.this).loadIntKey(
				MusicService.MUSIC_DURATION, n300000);
		if (0 == duration) {
			duration = n300000;
			mTvDuration.setText(mSdf.format(duration));
		} else {
			mTvDuration.setText(musicInfo.getTime());
		}
		mSkbMusic.setMax(duration);
		mCurrentMusic = musicInfo;

		if(musicInfo.isDownLoading()){
			showTopTipVIPTV(musicInfo.isHQ() && musicInfo.getHQId() > 0);//显示“vip特权介绍提示 ”by jwb
		}else{
			hideTopTipVIPTV();
		}
	}

	/**
	 * 返回键
	 * Created 2014-7-9 下午10:57:06
	 * @author zxq
	 */
	@Override
	public void onBackPressed() {
		if (View.VISIBLE == mLlVolume.getVisibility()) {
			mLlVolume.setVisibility(View.GONE);
			mLlDownload.setVisibility(View.GONE);
			return;
		}
		super.onBackPressed();
	}




}
